package com.czmh.etc.onlinepubsys.controller.cmg;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czmh.etc.common.core.utils.Sequence;
import com.czmh.etc.onlinepubsys.constants.cmg.BusinessType;
import com.czmh.etc.onlinepubsys.entity.mingchuang.ApplyInfo;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CurrentContext;
import com.czmh.etc.onlinepubsys.enums.cmg.ApiCodeEnum;
import com.czmh.etc.onlinepubsys.json.cmg.JSONResult;
import com.czmh.etc.onlinepubsys.model.EtcAfterSaleDevice;
import com.czmh.etc.onlinepubsys.model.EtcFallActivate;
import com.czmh.etc.onlinepubsys.model.EtcReplace;
import com.czmh.etc.onlinepubsys.request.cmg.*;
import com.czmh.etc.onlinepubsys.request.mingchuang.SubmitFallActivateRequest;
import com.czmh.etc.onlinepubsys.response.cmg.ApiResponseBase;
import com.czmh.etc.onlinepubsys.services.EtcAfterSaleDeviceService;
import com.czmh.etc.onlinepubsys.services.EtcFallActivateService;
import com.czmh.etc.onlinepubsys.services.EtcOrderService;
import com.czmh.etc.onlinepubsys.services.EtcReplaceService;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICurrentContextService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IEtcApplyService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IObuService;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import com.czmh.etc.onlinepubsys.utils.cmg.CmgHttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/{version}/api/cmg/ioapi/activate")
@Api(tags = "发行激活接口相关 - 招商局")
public class CmgActivateController {

    @Autowired
    private EtcFallActivateService etcFallActivateService;

    @Autowired
    private ICurrentContextService currentContextService;

    @Autowired
    private EtcOrderService etcOrderService;

    @Autowired
    private IObuService obuService;

    @Autowired
    private IEtcApplyService etcApplyService;

    @Value("${cmg.accessno}")
    private String accessno;

    @Value("${spring.profiles.active}")
    private String active;

    @Value("${cmg.authAccessNo}")
    private String authAccessNo;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private EtcAfterSaleDeviceService etcAfterSaleDeviceService;

    @Autowired
    private EtcReplaceService etcReplaceService;

    @PostMapping("/carDecrypt")
    @ApiOperation("车辆信息解密:脱落激活时需调用车辆信息解密来判断卡片车牌和OBU车牌号码是否一致")
    public JSONResult carDecrypt(@RequestBody CarDecryptRequest req) {
        JSONResult result = new JSONResult();
        log.info("carDecrypt:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.CARD_DECRYPT, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/confirmCard")
    @ApiOperation("写卡成功确认")
    public JSONResult confirmCard(@RequestBody ConfirmCardRequest req) {
        //该接口把数据提交缓存到用户当前流程数据表-用于保存该接口返回的短信版本号
        JSONResult result = new JSONResult();
        log.info("confirmCard:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ISSUE_ACTIVECONFIRM_CARD, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(req.getBussType() == 1){
                if(r.bizContent != null){
                    result.setRspData(r.getBizContent());
                    result.setMessage(r.getMsg());
                    result.setCurrentTime(r.getReceiveTime());
                    //写OBU成功确认操作成功之后把对应的请求信息和返回信息入库
                    CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
                    String jsonStr = currentContext.getJsonData();
                    JSONObject jsonObject = JSON.parseObject(jsonStr);
                    if(jsonObject == null){
                        jsonObject = new JSONObject();
                    }
                    jsonObject.put("confirmCardRequest", req);
                    jsonObject.put("confirmCardResponse", r);
                    currentContext.setEtcCardNo(req.getFaceCardNum());
                    currentContext.setJsonData(jsonObject.toJSONString());
                    currentContext.setBeginTime(req.getStartTime());
                    currentContext.setEndTime(req.getEndTime());
                    currentContext.setBeginDate(req.getBeginDate());
                    currentContext.setEndDate(req.getEndDate());
                    //招商单片流程状态和联合单片同步
                    currentContext.setState(5);
                    currentContextService.update(currentContext);
                    //按照铭创流程逻辑操作激活成功之后的操作
                    obuService.cmgActiveComplete(currentContext.getObuId(), req.getUserId());
                }
            }
            if(req.getBussType() == 2 && (req.getType() == 1 || req.getType() == 3)){
                if(r.bizContent != null){
                    //检查售后设备表是否存在对应的设备信息
                    Map<String, Object> queryMap = new HashMap<>();
                    queryMap.put("deleteFlag", "0");
                    queryMap.put("type", "1");
                    queryMap.put("deviceSn", req.getFaceCardNum());
                    queryMap.put("activeStatus", "0");
                    List<EtcAfterSaleDevice> list = etcAfterSaleDeviceService.queryList(queryMap);
                    if(!CollectionUtils.isEmpty(list)){
                        //更新售后设备表对应的设备激活信息
                        EtcAfterSaleDevice etcAfterSaleDevice = list.get(0);
                        etcAfterSaleDevice.setActiveStatus(1);
                        etcAfterSaleDevice.setActiveTime(new Date());
                        etcAfterSaleDevice.setOrderId(req.getOrderId());
                        etcAfterSaleDeviceService.update(etcAfterSaleDevice);
                    }

                    //同步更新更换记录状态
                    Map<String, Object> map = new HashMap<>();
                    map.put("deleteFlag", "0");
                    map.put("type", "1");
                    map.put("deviceSn", req.getOldFaceCardNum());
                    map.put("orderId", req.getOrderId());
                    map.put("activeStatus", "0");
                    List<EtcReplace> l = etcReplaceService.queryList(map);
                    if(!CollectionUtils.isEmpty(list)){
                        //更新售后设备表对应的设备激活信息
                        EtcReplace e = l.get(0);
                        e.setStatus(1);
                        etcReplaceService.update(e);
                    }
                }
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/confirmObu")
    @ApiOperation("写OBU成功确认")
    public JSONResult confirmObu(@RequestBody ConfirmObuRequest req) {
        //该接口把数据提交缓存到用户当前流程数据表-用于保存该接口返回的短信版本号
        JSONResult result = new JSONResult();
        log.info("confirmObu:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ISSUE_ACTIVE_CONFIRM_OBU, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(req.getBussType() == 1){
                if(r.bizContent != null){
                    result.setRspData(r.getBizContent());
                    result.setMessage(r.getMsg());
                    result.setCurrentTime(r.getReceiveTime());
                    //写OBU成功确认操作成功之后把对应的请求信息和返回信息入库
                    CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
                    String jsonStr = currentContext.getJsonData();
                    JSONObject jsonObject = JSON.parseObject(jsonStr);
                    if(jsonObject == null){
                        jsonObject = new JSONObject();
                    }
                    jsonObject.put("confirmObuRequest", req);
                    jsonObject.put("confirmObuResponse", r);
                    currentContext.setObuId(req.getSerialNumber());
                    currentContext.setJsonData(jsonObject.toJSONString());
                    currentContextService.update(currentContext);
                }
            }
            if(req.getBussType() == 2 && (req.getType() == 2 || req.getType() == 3)){
                if(r.bizContent != null){
                    //检查售后设备表是否存在对应的设备信息
                    Map<String, Object> queryMap = new HashMap<>();
                    queryMap.put("deleteFlag", "0");
                    queryMap.put("type", "2");
                    queryMap.put("deviceSn", req.getSerialNumber());
                    queryMap.put("activeStatus", "0");
                    List<EtcAfterSaleDevice> list = etcAfterSaleDeviceService.queryList(queryMap);
                    if(!CollectionUtils.isEmpty(list)){
                        //更新售后设备表对应的设备激活信息
                        EtcAfterSaleDevice etcAfterSaleDevice = list.get(0);
                        etcAfterSaleDevice.setActiveStatus(1);
                        etcAfterSaleDevice.setActiveTime(new Date());
                        etcAfterSaleDevice.setOrderId(req.getOrderId());
                        etcAfterSaleDeviceService.update(etcAfterSaleDevice);
                    }

                    //同步更新更换记录状态
                    Map<String, Object> map = new HashMap<>();
                    map.put("deleteFlag", "0");
                    map.put("type", "2");
                    map.put("deviceSn", req.getOldSerialNumber());
                    map.put("orderId", req.getOrderId());
                    map.put("activeStatus", "0");
                    List<EtcReplace> l = etcReplaceService.queryList(map);
                    if(!CollectionUtils.isEmpty(list)){
                        //更新售后设备表对应的设备激活信息
                        EtcReplace e = l.get(0);
                        e.setStatus(1);
                        etcReplaceService.update(e);
                    }
                }
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/queryIssueActive")
    @ApiOperation("卡签发行状态查询:第三方系统发行卡签之前，需要该车辆有办理的业务订单，先写OBU后写卡，\n" +
            "写OBU应按车辆信息、系统信息的顺序写：\n" +
            "若写某个文件失败，应该重新写一遍；例如写卡状态是1、写车辆信息成功则第三方应该重新从写车辆信\n" +
            "息文件开始重写;\n" +
            "只有当所有文件都写成功后，才调用写OBU成功确认接口；\n" +
            "写卡应按0015、0016的顺序写：\n" +
            "若写某个文件失败，应该重新写一遍；例如写卡状态是1、写0016文件成功则第三方应该重新从0016文\n" +
            "件开始重写;\n" +
            "只有当所有文件都写成功后，才调用写卡成功确认接口；\n" +
            "备注：如果卡/OBU反复写都是失败的话，则怀疑是卡/OBU质量问题，可以通过补换卡/OBU重新发行。")
    public JSONResult queryIssueActive(@RequestBody QueryIssueActiveRequest req) {
        JSONResult result = new JSONResult();
        log.info("queryIssueActive:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ISSUE_ACTIVE_QUERY, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
                //由于用户已经完成激活，所以会出现没有新的申请流程数据导致提示逻辑有问题
/*                CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
                if(currentContext == null){
                    result.setCode(JSONResult.FAIL);
                    result.setCurrentTime("" + System.currentTimeMillis());
                    result.setMessage("该用户不在申办流程当中！");
                }else{
                    String jsonStr = currentContext.getJsonData();
                    JSONObject jsonObject = JSON.parseObject(jsonStr);
                    if(jsonObject == null){
                        jsonObject = new JSONObject();
                    }
                    jsonObject.put("queryIssueActive", r.getBizContent());
                    currentContext.setJsonData(jsonObject.toJSONString());
                    currentContextService.update(currentContext);
                }*/
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/reActiveConfirm")
    @ApiOperation("OBU脱落激活确认")
    public JSONResult reActiveConfirm(@RequestBody ReActiveConfirmRequest req) {
        JSONResult result = new JSONResult();
        log.info("reActiveConfirm:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.RE_ACTIVE_CONFIRM, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/reActiveObu")
    @ApiOperation("获取脱落激活指令:需要选择OBU目录，以指令+MAC码进行写OBU")
    public JSONResult reActiveObu(@RequestBody ReActiveObuRequest req) {
        JSONResult result = new JSONResult();
        log.info("reActiveObu:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.RE_ACTIVE_OBU, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/sendMsg")
    @ApiOperation("发送卡签发行激活校验短信:成功返回短信版本号")
    public JSONResult sendMsg(@RequestBody SendMsgRequest req) {
        //该接口把数据提交缓存到用户当前流程数据表-用于保存该接口返回的短信版本号，方便后面接口引用该参数
        JSONResult result = new JSONResult();
        log.info("sendMsg:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ISSUE_ACTIVE_SEND_MSG, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/uploadPic")
    @ApiOperation("发行激活上传图片")
    public JSONResult uploadPic(@RequestBody UploadPicRequest req) {
        UploadPicRequest request = JSON.parseObject(JSON.toJSONString(req), UploadPicRequest.class);
        request.setPicData("");
        //该接口把数据提交缓存到用户当前流程数据表
        JSONResult result = new JSONResult();
        log.info("uploadPic:{}", JSON.toJSONString(request));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ISSUE_ACTIVE_UPLOAD_PIC, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
                if(req.getType() == 0){
                    CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
                    if(currentContext == null){
                        result.setCode(JSONResult.FAIL);
                        result.setCurrentTime("" + System.currentTimeMillis());
                        result.setMessage("该用户不在申办流程当中！");
                    }
                    String jsonStr = currentContext.getJsonData();
                    JSONObject jsonObject = JSON.parseObject(jsonStr);
                    if(jsonObject == null){
                        jsonObject = new JSONObject();
                    }
                    req.setPicData("");
                    jsonObject.put("uploadPicRequest", req);
                    currentContext.setJsonData(jsonObject.toJSONString());
                    currentContextService.update(currentContext);
                }
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/verifymsg")
    @ApiOperation("卡签验证码校验接口")
    public JSONResult verifymsg(@RequestBody VerifyMsgRequest req) {
        JSONResult result = new JSONResult();
        //非正是环境直接返回true，方便测试开发
//        if(!active.equalsIgnoreCase("pro")){
//            result.setCode(JSONResult.SUCCESS);
//            result.setCurrentTime("" + System.currentTimeMillis());
//            return result;
//        }
        log.info("verifymsg:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ISSUE_ACTIVE_VERIFY_MSG, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/write0015")
    @ApiOperation("获取卡片0015文件写卡指令:需要选择卡片目录，以指令+MAC码进行写卡")
    public JSONResult write0015(@RequestBody Write0015IssueActiveRequest req) {
        JSONResult result = new JSONResult();
        log.info("write0015:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ISSUE_ACTIVE_WRITE0015, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/write0016")
    @ApiOperation("获取卡片0016文件写卡指令:需要选择卡片目录，以指令+MAC码进行写卡")
    public JSONResult write0016(@RequestBody Write0016IssueActiveRequest req) {
        JSONResult result = new JSONResult();
        log.info("write0016:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
/*
        //更换卡签业务需要判断对应的设备是否存在售后信息表当中
        if(req.getBussType() == 2){
            //检查售后设备表是否存在对应的设备信息
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("type", "2");
            queryMap.put("deviceSn", req.getFaceCardNum());
            queryMap.put("activeStatus", "0");
            List<EtcAfterSaleDevice> list = etcAfterSaleDeviceService.queryList(queryMap);
            if(CollectionUtils.isEmpty(list)){
                result.setCode(JSONResult.FAIL);
                result.setMessage("设备不存在！");
                result.setCurrentTime("" + time);
                return result;
            }

            //检查ETC卡是否被激活绑定
            Map<String, Object> map = new HashMap<>();
            map.put("deleteFlag", "0");
            map.put("etcSn", req.getFaceCardNum());
            map.put("activeStatus", "1");
            EtcDevice etcDevice = etcOrderService.queryObject(map);
            if(etcDevice != null){
                result.setCode(JSONResult.FAIL);
                result.setMessage("设备不存在！!");
                result.setCurrentTime("" + time);
                return result;
            }
        }*/

        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ISSUE_ACTIVE_WRITE0016, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/writeSystem")
    @ApiOperation("获取写系统信息指令:需要选择OBU目录，以指令+MAC码进行写OBU")
    public JSONResult writeSystem(@RequestBody WriteSystemRequest req) {
        JSONResult result = new JSONResult();
        log.info("writeSystem:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ISSUE_ACTIVE_WRITE_SYSTEM, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/bindCardObu")
    @ApiOperation("卡签发行绑定接口")
    public JSONResult bindCardObu(@RequestBody BindCardObuRequest req) {
        JSONResult result = new JSONResult();
        log.info("bindCardObu:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ISSUE_ACTIVE_BIND_CAR_OBU, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/writeVehicle")
    @ApiOperation("获取写车辆信息指令：需要选择OBU目录，以指令+MAC码进行写OBU")
    public JSONResult writeVehicle(@RequestBody WriteVehicleRequest req) {
        JSONResult result = new JSONResult();
        log.info("writeVehicle:{}", JSON.toJSONString(req));
        //为操作填充订单号信息
        if(req.getBussType() == 1){
            CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
            if(currentContext != null && StringUtils.isNotEmpty(currentContext.getOrderNo())){
                req.setOrderId(currentContext.getOrderNo());
                req.setSupplier("西藏");
            }else{
                result.setCode(JSONResult.FAIL);
                result.setMessage("当前用户不在申请流程中");
                return result;
            }
        }
        Long time = System.currentTimeMillis();
/*

        //更换卡签业务需要判断对应的设备是否存在售后信息表当中
        if(req.getBussType() == 2){
            //检查售后设备表是否存在对应的设备信息
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("deleteFlag", "0");
            queryMap.put("type", "2");
            queryMap.put("deviceSn", req.getSerialNumber());
            queryMap.put("activeStatus", "0");
            List<EtcAfterSaleDevice> list = etcAfterSaleDeviceService.queryList(queryMap);
            if(CollectionUtils.isEmpty(list)){
                result.setCode(JSONResult.FAIL);
                result.setMessage("设备不存在！");
                result.setCurrentTime("" + time);
                return result;
            }

            //检查OBU是否被激活绑定
            Map<String, Object> map = new HashMap<>();
            map.put("deleteFlag", "0");
            map.put("obuDeviceSn", req.getSerialNumber());
            map.put("activeStatus", "1");
            EtcDevice etcDevice = etcOrderService.queryObject(map);
            if(etcDevice != null){
                result.setCode(JSONResult.FAIL);
                result.setMessage("设备不存在！!");
                result.setCurrentTime("" + time);
                return result;
            }
        }
*/

        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ISSUE_ACTIVE_WRITE_VEHICLE, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/submitFallActivateInfo")
    @ApiOperation("提交脱离激活用户信息")
    public JSONResult submitFallActivateInfo(@RequestBody SubmitFallActivateRequest req) {
        JSONResult result = new JSONResult();
        log.info("提交脱离激活用户信息:{}", JSON.toJSONString(req));
        if(null == req){
            result.setCode(JSONResult.FAIL);
            result.setMessage("请求参数异常，请检查");
            return result;
        }
        Date date = new Date();
        EtcFallActivate etcFallActivate = new EtcFallActivate();
        etcFallActivate.setId(Sequence.getId());
        etcFallActivate.setDeleteFlag(0);
        etcFallActivate.setEtcSn(req.getEtcSn());
        etcFallActivate.setImages(req.getImages());
        etcFallActivate.setName(req.getName());
        etcFallActivate.setObuDeviceSn(req.getObuDeviceSn());
        etcFallActivate.setOrderId(req.getOrderId());
        etcFallActivate.setStatus(0);
        etcFallActivate.setChannelType(1);
        etcFallActivate.setVehiclePlate(req.getVehiclePlate());
        etcFallActivate.setUserId(req.getUserId());
        etcFallActivate.setUpdatedTime(date);
        etcFallActivate.setCreateTime(date);
        etcFallActivate.setApplyTime(date);
        int r = etcFallActivateService.save(etcFallActivate);
        if(r > 0){
            JSONObject json = new JSONObject();
            json.put("etcFallActivateId", etcFallActivate.getId());
            result.setRspData(json.toJSONString());
        }else{
            result.setCode(JSONResult.FAIL);
            result.setMessage("信息提交失败");
        }
        return result;
    }

    @PostMapping("/updateFallActivateStatus")
    @ApiOperation("更新脱离激活状态")
    public JSONResult updateFallActivateStatus(@ApiParam(value = "脱离激活申请信息ID") @RequestParam String etcFallActivateId, @ApiParam(value = "激活结果") @RequestParam Integer status) {
        JSONResult result = new JSONResult();
        log.info("更新脱离激活状态:{}", etcFallActivateId);
        if(null == etcFallActivateId){
            result.setCode(JSONResult.FAIL);
            result.setMessage("请求参数异常，请检查");
            return result;
        }
        EtcFallActivate etcFallActivate = etcFallActivateService.queryObject(etcFallActivateId);
        Date date = new Date();
        etcFallActivate.setStatus(status);
        etcFallActivate.setUpdatedTime(date);
        int r = etcFallActivateService.update(etcFallActivate);
        if(r > 0){
            JSONObject json = new JSONObject();
            json.put("etcFallActivateId", etcFallActivate.getId());
            result.setRspData(json.toJSONString());
        }else{
            result.setCode(JSONResult.FAIL);
            result.setMessage("更新脱离激活状态失败");
        }
        return result;
    }

    @PostMapping("/getToken")
    @ApiOperation("获取授权访问token接口")
    public JSONResult getToken(@RequestBody GetTokenRequest req) {
        JSONResult result = new JSONResult();
        log.info("getToken:{}", JSON.toJSONString(req));
        //为操作填充订单号信息
        CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
        //根据前端要求不对用户流程进行判断
/*        if(currentContext != null && StringUtils.isNotEmpty(currentContext.getOrderNo())){
        }else{
            result.setCode(JSONResult.FAIL);
            result.setMessage("当前用户不在申请流程中");
            return result;
        }*/
        Long time = System.currentTimeMillis();
        req.setTime(time);
        req.setAuthAccessNo(authAccessNo);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.AUTH_GET_TOKEN, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
                //手机请求结果数据不改变用户请求流程状态
                //currentContext.setState(4);
                //判断流程是否存在
                if(currentContext != null && StringUtils.isNotEmpty(currentContext.getOrderNo())){
                    String jsonStr = currentContext.getJsonData();
                    JSONObject jsonObject = JSON.parseObject(jsonStr);
                    if(jsonObject == null){
                        jsonObject = new JSONObject();
                    }
                    jsonObject.put("getToken", r);
                    currentContext.setJsonData(jsonObject.toJSONString());
                    currentContextService.update(currentContext);
                }else{
                    log.info("用户不在流程：", req.getUserId());
                }
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/updateStatus")
    @ApiOperation("用户ETC申请状态变更,微信签约授权成功")
    public JSONResult updateStatus(@RequestBody UpdateStatusRequest req) {
        log.info("ETC申请状态变更:{}", JSON.toJSONString(req));
        JSONResult result = new JSONResult();
        result.setCode(JSONResult.SUCCESS);
        result.setCurrentTime("" + System.currentTimeMillis());
        if(req == null || req.getUserId() == null){
            result.setCode(JSONResult.FAIL);
            result.setMessage("userId不能为空！");
        }
        QueryWrapper<CurrentContext> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", req.getUserId());
        wrapper.eq("state", 3);
        wrapper.eq("delete_flag", 0);
        wrapper.eq("pay_mode", 1);
        List<CurrentContext> currentContextList = currentContextService.queryObjects(wrapper);
        if (CollectionUtils.isEmpty(currentContextList)) {
            result.setCode(JSONResult.FAIL);
            result.setCurrentTime("" + System.currentTimeMillis());
            result.setMessage("该用户不在申办流程当中！");
        } else {
            CurrentContext currentContext = currentContextList.get(0);
            String jsonStr = currentContext.getJsonData();
            JSONObject jsonObject = JSON.parseObject(jsonStr);
            if(jsonObject == null){
                jsonObject = new JSONObject();
            }
            jsonObject.put("wxAuthState", 1);
            jsonObject.put("extraData", req.getExtraData());
            currentContext.setJsonData(jsonObject.toJSONString());
            currentContextService.update(currentContext);
            ApplyInfo applyInfo = etcApplyService.get(currentContext.getApplyId());
            if(applyInfo != null){
                applyInfo.setBankSignTime(new Date());
                applyInfo.setBankCardType(3);
                applyInfo.setState(1);
                etcApplyService.update(applyInfo);
            }
        }
        return result;
    }

}
